$(document).ready(function() {
    // 显示加载动画
    function showLoading() {
        $('.loading-container').fadeIn(200);
    }

    // 隐藏加载动画
    function hideLoading() {
        $('.loading-container').fadeOut(200);
    }

    // 渲染菜单
    function renderMenu(menuData, parentElement = null) {
        const $container = parentElement || $('#menu');
        
        menuData.forEach(item => {
            if (item.children && item.children.length) {
                // 创建分组容器
                const $group = $(`
                    <div class="accordion-item">
                        <h2 class="accordion-header">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                    data-bs-target="#menu-${item.name}">
                                ${item.name}
                            </button>
                        </h2>
                        <div id="menu-${item.name}" class="accordion-collapse collapse">
                            <div class="accordion-body p-0">
                                <div class="nav flex-column"></div>
                            </div>
                        </div>
                    </div>
                `);
                
                // 递归渲染子菜单
                renderMenu(item.children, $group.find('.nav'));
                $container.append($group);
            } else if (item.path) {
                // 创建菜单项
                const $item = $(`
                    <a class="nav-link" href="#" 
                       data-path="${item.path}" 
                       data-name="${item.name}"
                       data-breadcrumb="${getBreadcrumb(item, menuData)}">
                        <span class="d-flex justify-content-between align-items-center">
                            ${item.name}
                            ${item.method ? `<small class="badge ${item.method} bg-light text-dark ms-1">${item.method}</small>` : ''}
                        </span>
                    </a>
                `);
                $container.append($item);
            }
        });
    }

    // 获取面包屑路径
    function getBreadcrumb(item, menuData, path = []) {
        path.unshift(item.name);
        
        // 递归查找父级
        function findParent(items) {
            for (const menuItem of items) {
                if (menuItem.children) {
                    const found = menuItem.children.some(child => {
                        if (child === item) {
                            path.unshift(menuItem.name);
                            return true;
                        }
                        return findParent([child]);
                    });
                    if (found) return true;
                }
            }
            return false;
        }
        
        findParent(menuData);
        return path.join(',');
    }

    // 更新面包屑导航
    function updateBreadcrumb(breadcrumb) {
        const paths = breadcrumb.split(',');
        const $breadcrumb = $('#breadcrumb');
        
        // 清除现有的面包屑（保留首页）
        $breadcrumb.find('li:not(:first-child)').remove();
        
        // 添加面包屑路径
        paths.forEach((name, index) => {
            $breadcrumb.append(`
                <li class="breadcrumb-item${index === paths.length - 1 ? ' active' : ''}">
                    ${name}
                </li>
            `);
        });
    }

    // 首页链接点击事件
    $(document).on('click', '.home-link', function(e) {
        e.preventDefault();
        
        // 更新面包屑
        $('#breadcrumb').html(`
            <li class="breadcrumb-item">
                <a href="#" class="home-link">首页</a>
            </li>
        `);
        
        // 清除菜单选中状态
        $('.nav-link').removeClass('active');
        
        // 加载欢迎页面
        showLoading();
        $('#docFrame').attr('src', '/docs/welcome.html');
    });

    // 加载菜单
    fetch('/docs/config.json')
        .then(response => response.json())
        .then(config => {
            renderMenu(config.menu);
        });

    // 菜单点击事件
    $(document).on('click', '.nav-link[data-path]', function(e) {
        e.preventDefault();
        const $link = $(this);
        const path = $link.data('path');
        const breadcrumb = $link.data('breadcrumb');

        // 更新面包屑
        updateBreadcrumb(breadcrumb);

        // 更新选中状态
        $('.nav-link').removeClass('active');
        $link.addClass('active');

        // 展开所有父级菜单
        let $parent = $link.closest('.accordion-collapse');
        while ($parent.length) {
            $parent.addClass('show');
            $parent = $parent.parent().closest('.accordion-collapse');
        }

        if (path) {
            showLoading();
            $('#docFrame').attr('src', '/docs/' + path);
        }
        
        // 移动端自动关闭侧边栏
        if ($(window).width() <= 768) {
            $('.sidebar').removeClass('show');
            $('.menu-toggle').removeClass('active');
        }
    });

    // 监听 iframe 加载完成
    $('#docFrame').on('load', function() {
        hideLoading();
    });

    // 搜索功能
    $('#searchInput').on('input', function() {
        const searchText = $(this).val().toLowerCase();
        $('.nav-link[data-path]').each(function() {
            const $link = $(this);
            const name = $link.data('name').toLowerCase();
            const group = $link.data('group').toLowerCase();
            const visible = name.includes(searchText) || group.includes(searchText);
            $link.toggle(visible);
        });
    });

    // 菜单折叠按钮点击事件
    $('.menu-toggle').click(function() {
        $(this).toggleClass('active');
        $('.sidebar').toggleClass('show');
    });

    // 点击遮罩层关闭菜单
    $(document).click(function(e) {
        if ($(window).width() <= 768) {
            if (!$(e.target).closest('.sidebar').length && 
                !$(e.target).closest('.menu-toggle').length) {
                $('.sidebar').removeClass('show');
                $('.menu-toggle').removeClass('active');
            }
        }
    });

    // 关闭按钮点击事件
    $('.close-sidebar').click(function() {
        $('.sidebar').removeClass('show');
        $('.menu-toggle').removeClass('active');
    });

    // 窗口大小改变时处理
    $(window).resize(function() {
        if ($(window).width() > 768) {
            $('.sidebar').removeClass('show');
            $('.menu-toggle').removeClass('active');
        }
    });
}); 